<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\model\CourseModel;
use app\model\CoursesReviewsModel;
use app\model\CoursesUsersLikeModel;
use app\model\CourseUserRecordsModel;
use app\model\RedisModel;
use app\model\UserModel;
use think\App;
use think\facade\Db;

class CourseUserRecords extends Base {

    private $req;

    private $uid;

    private $courseUserRecordsModel;

    private $courseModel;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->courseUserRecordsModel = new CourseUserRecordsModel();

        $this->courseModel = new CourseModel();

        $this->uid = $this->isLogin();
    }


    /*
     * 商品评价
     *
     * */
    public function startStudy(){

        if(!$this->req["course_id"]){
            return $this->fail("请选择要点赞的评价");
        }

        $where =[];
        $where[] = ['course_id','=',$this->req["course_id"]];
        $where[] = ['uid','=',$this->uid];

        $info = $this->courseUserRecordsModel->where($where)->find();
        if($info){
            $recordsRes = $this->courseUserRecordsModel->where("course_record_id",$info["course_record_id"])->save([
                "last_time"=>date("Y-m-d H:i:s")
            ]);

            if($recordsRes){
                return $this->succ("播放更新成功");
            }else{
                return $this->fail("播放更新失败");
            }
        }else{
            Db::startTrans();
            $recordsRes = $this->courseUserRecordsModel->insertGetId([
                "uid"=>$this->uid,
                "course_id"=>$this->req["course_id"],
                "last_time"=>date("Y-m-d H:i:s")
            ]);
            $courseRes = $this->courseModel->where([
                "course_id"=>$this->req["course_id"],
            ])->inc("view_num",1)->update();

            if($recordsRes && $courseRes){
                Db::commit();
                return $this->succ("播放记录成功");
            }else{
                Db::rollback();
                return $this->fail("播放记录失败");
            }
        }
    }

}
